#pragma once

#include <cstdlib>
#include <cstring>

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

#include "Log.hpp"

#define BACKLOG 5

class TcpServer
{
private:
    TcpServer(int port) : _port(port), _listenSock(-1)
    {
    }
    TcpServer(const TcpServer &x) = delete;

public:
    static TcpServer *GetInstance(int port)
    {
        if (nullptr == _svr)
        {
            static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
            if (nullptr == _svr)
            {
                pthread_mutex_lock(&lock);
                if (nullptr == _svr)
                {
                    _svr = new TcpServer(port);
                    _svr->InitServer();
                }
                pthread_mutex_unlock(&lock);
            }
        }
        return _svr;
    }
    void InitServer()
    {
        Socket();
        Bind();
        Listen();
        LOG(INFO, "tcp_server init success");
    }

    void Socket()
    {
        _listenSock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listenSock < 0)
        {
            LOG(FATAL, "socket error!");
            exit(1);
        }
        LOG(INFO, "create socket success");

        int opt = 1;
        setsockopt(_listenSock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    }
    void Bind()
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        if (bind(_listenSock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            LOG(FATAL, "bind error!");
            std::cout << _listenSock << std::endl;
            std::cout << errno << strerror(errno) << std::endl;
            exit(2);
        }
        LOG(INFO, "bind socket success");
    }
    void Listen()
    {
        if (listen(_listenSock, BACKLOG) < 0)
        {
            LOG(FATAL, "listen error!");
            exit(3);
        }
        LOG(INFO, "listen socket success");
    }
    int Sock()
    {
        return _listenSock;
    }
    ~TcpServer()
    {
        if (_listenSock >= 0)
        {
            close(_listenSock);
        }
    }

private:
    int _port;
    int _listenSock;
    static TcpServer *_svr;
};
TcpServer *TcpServer::_svr = nullptr;